from tkinter import *
from tkinter import ttk, filedialog, messagebox
from datetime import datetime
from db_operations import DBOperations
import os

class InboundUI:
    def __init__(self, root):
        self.root = root
        self.db = DBOperations()
        self.photo_path = None
        
        self.frame = Frame(self.root, padx=20, pady=20)
        self.frame.pack(expand=True)
        
        # 日期
        Label(self.frame, text="日期:").grid(row=0, column=0, sticky=W, pady=5)
        self.date_label = Label(self.frame, text=datetime.now().strftime('%Y-%m-%d'))
        self.date_label.grid(row=0, column=1, sticky=W, pady=5)
        
        # SN码
        Label(self.frame, text="SN码:").grid(row=1, column=0, sticky=W, pady=5)
        self.sn_entry = Entry(self.frame)
        self.sn_entry.grid(row=1, column=1, pady=5)
        Button(self.frame, text="扫码", command=self.scan_sn).grid(row=1, column=2, padx=5)
        
        # 设备型号
        Label(self.frame, text="设备型号:").grid(row=2, column=0, sticky=W, pady=5)
        self.model_entry = Entry(self.frame)
        self.model_entry.grid(row=2, column=1, pady=5)
        Button(self.frame, text="识别", command=self.recognize_model).grid(row=2, column=2, padx=5)
        
        # 生产厂商
        Label(self.frame, text="生产厂商:").grid(row=3, column=0, sticky=W, pady=5)
        self.manufacturer_combo = ttk.Combobox(self.frame, values=["华为", "中兴", "烽火", "其他"])
        self.manufacturer_combo.grid(row=3, column=1, pady=5)
        self.manufacturer_combo.set("华为")
        
        # 拆除的网元名称
        Label(self.frame, text="拆除的网元名称:").grid(row=4, column=0, sticky=W, pady=5)
        self.network_entry = Entry(self.frame)
        self.network_entry.grid(row=4, column=1, pady=5)
        Button(self.frame, text="导入清单", command=self.import_network_list).grid(row=4, column=2, padx=5)
        
        # 设备类型
        Label(self.frame, text="设备类型:").grid(row=5, column=0, sticky=W, pady=5)
        self.type_combo = ttk.Combobox(self.frame, values=["BBU", "RRU", "天线", "基带板", "其他"])
        self.type_combo.grid(row=5, column=1, pady=5)
        self.type_combo.set("BBU")
        
        # 制式
        Label(self.frame, text="制式:").grid(row=6, column=0, sticky=W, pady=5)
        self.standard_combo = ttk.Combobox(self.frame, values=["2G", "4G", "5G"])
        self.standard_combo.grid(row=6, column=1, pady=5)
        self.standard_combo.set("5G")
        
        # 设备照片
        Label(self.frame, text="设备照片:").grid(row=7, column=0, sticky=W, pady=5)
        self.photo_button = Button(self.frame, text="上传照片", command=self.upload_photo)
        self.photo_button.grid(row=7, column=1, pady=5)
        
        # 提交按钮
        Button(self.frame, text="提交", command=self.submit).grid(row=8, column=1, pady=20)
    
    def scan_sn(self):
        # 扫码识别上传的图片
        if not self.photo_path:
            messagebox.showerror("错误", "请先上传设备照片")
            return
        try:
            from pyzbar.pyzbar import decode, ZBarSymbol
            from PIL import Image
        except ImportError:
            messagebox.showerror("错误", "缺少pyzbar或Pillow库，请先安装依赖")
            return
        try:
            img = Image.open(self.photo_path)
            # 识别Data Matrix和CODE 128
            results = decode(img, symbols=[ZBarSymbol.DATAMATRIX, ZBarSymbol.CODE128])
            if results:
                sn = results[0].data.decode('utf-8')
                self.sn_entry.delete(0, END)
                self.sn_entry.insert(0, sn)
            else:
                messagebox.showwarning("未识别", "未识别到Data Matrix或CODE 128条码")
        except Exception as e:
            messagebox.showerror("错误", f"识别失败: {e}")
    
    def recognize_model(self):
        # 模拟识别设备型号
        self.model_entry.delete(0, END)
        self.model_entry.insert(0, "MODEL" + str(datetime.now().timestamp()).replace(".", "")[:6])
    
    def import_network_list(self):
        # 模拟导入网元清单
        filepath = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx")])
        if filepath:
            self.network_entry.delete(0, END)
            self.network_entry.insert(0, os.path.basename(filepath))
    
    def upload_photo(self):
        # 上传设备照片
        filepath = filedialog.askopenfilename(filetypes=[("图片文件", "*.jpg *.png")])
        if filepath:
            self.photo_path = filepath
            self.photo_button.config(text="已上传: " + os.path.basename(filepath))
    
    def submit(self):
        # 验证必填字段
        if not self.sn_entry.get():
            messagebox.showerror("错误", "SN码不能为空")
            return
        
        if not self.model_entry.get():
            messagebox.showerror("错误", "设备型号不能为空")
            return
        
        # 准备数据
        data = {
            'sn': self.sn_entry.get(),
            'model': self.model_entry.get(),
            'manufacturer': self.manufacturer_combo.get(),
            'network_element': self.network_entry.get(),
            'type': self.type_combo.get(),
            'standard': self.standard_combo.get(),
            'photo_path': self.photo_path
        }
        
        # 保存到数据库
        if self.db.add_equipment(data):
            messagebox.showinfo("成功", "设备入库成功")
            self.clear_form()
        else:
            messagebox.showerror("错误", "SN码已存在")
    
    def clear_form(self):
        # 清空表单
        self.sn_entry.delete(0, END)
        self.model_entry.delete(0, END)
        self.network_entry.delete(0, END)
        self.photo_button.config(text="上传照片")
        self.photo_path = None